/** @format */

import axios from 'axios-miniprogram'
import { buildGiteeUrl } from '../utils/commonUtils'

export class GiteeService {
  private accessToken = 'f7ac1fb39c02940ba347c526f9cbf19c'

  async getFileContentByUrl(path: string, json: boolean = false) {
    try {
      const response = await axios.get(
        path,
        {},
        {
          headers: {
            Authorization: `token ${this.accessToken}`,
          },
        }
      )

      let { content, ...rest } = response.data as any
      // content 存在时，才处理
      if (content) content = this.base64Decode(content)

      if (json) {
        if (content) {
          try {
            content = JSON.parse(content)
          } catch (e) {
            console.log('json error')
            content = {}
          }
        } else {
          content = {}
        }
      }
      rest.content = content
      return rest
    } catch (error) {
      console.error('获取文件内容失败:', error, path)
      throw error
    }
  }

  async updateFileContentByUrl(url: string, data: any) {
    const { sha, content } = data
    if (!sha) {
      // 创建文件
      const res = await axios.post(
        url,
        {
          message: 'feat: Create file',
          content: this.base64Encode(content),
        },
        {
          headers: {
            Authorization: `token ${this.accessToken}`,
          },
        }
      )
      return res
    } else {
      // 更新文件
      const res = await axios.put(
        url,
        {
          message: 'feat: Update file',
          content: this.base64Encode(content),
          sha,
        },
        {
          headers: {
            Authorization: `token ${this.accessToken}`,
          },
        }
      )
      return res
    }
  }

  async getFileContent(
    owner: string,
    repo: string,
    path: string,
    json: boolean = false
  ) {
    return this.getFileContentByUrl(buildGiteeUrl(owner, repo, path), json)
  }

  async getDirectoryContents(owner: string, repo: string, path: string) {
    try {
      const response = await axios.get(
        buildGiteeUrl(owner, repo, path),
        {},
        {
          headers: {
            Authorization: `token ${this.accessToken}`,
          },
        }
      )
      return response.data
    } catch (error) {
      console.error('获取目录内容失败:', error)
      throw error
    }
  }

  private base64Decode(base64: string): string {
    const binaryString = uni.base64ToArrayBuffer(base64)
    const uint8Array = new Uint8Array(binaryString)
    let decodedString = ''

    for (let i = 0; i < uint8Array.length; i++) {
      decodedString += String.fromCharCode(uint8Array[i])
    }

    return decodeURIComponent(escape(decodedString))
  }

  private stringToArrayBuffer(str: string): ArrayBuffer {
    const buf = new ArrayBuffer(str.length) // 使用2字节处理UTF-8
    const bufView = new Uint8Array(buf)
    for (let i = 0, strLen = str.length; i < strLen; i++) {
      bufView[i] = str.charCodeAt(i)
    }
    return buf
  }

  private base64Encode(data: Object): string {
    const content = JSON.stringify(data, null, 2)
    const buf = this.stringToArrayBuffer(unescape(encodeURIComponent(content)))
    return uni.arrayBufferToBase64(buf)
  }
}
